package com.ilxqx.fierce.core;

import org.springframework.beans.TypeConverter;
import org.springframework.core.MethodParameter;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;

/**
 * 参数处理器
 *
 * @author Venus
 * @since 1.0.0
 */
public final class ActionMethodHandlerDelegate {

    /**
     * 调用动作方法
     *
     * @param target 目标对象
     * @param targetClass 目标类
     * @param method 方法对象
     * @param requestData 请求数据
     * @return 结果
     */
    static Object invokeAction(Object target, Class<?> targetClass, Method method, Map<String, Object> requestData) {
        ActionMethod actionMethod = ActionMethodHolder.getActionMethod(target, targetClass, method);

        MethodParameter[] methodParameters = actionMethod.getMethodParameters();
        TypeConverter typeConverter = FierceRequestProcessingSupport.getTypeConverter();
        Object[] args = new Object[methodParameters.length];
        for (MethodParameter methodParameter : methodParameters) {
            Parameter parameter = methodParameter.getParameter();
            Object value = requestData.get(parameter.getName());
            // 转换
            args[methodParameter.getParameterIndex()] = typeConverter.convertIfNecessary(value, parameter.getType(), methodParameter);
        }

        // 调用动作
        return ActionInvokerDelegate.invokeAction(actionMethod, target, args);
    }
}
